/* arch/x86_64/boot/boot.S 
 * 
 * This file is part of xnix. 
 * 
 * XNIX is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * XNIX is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with XNIX. If not, see <https://www.gnu.org/licenses/>
 */ 




.code16


/* load system to 0x8000, and boot */

.globl _start

_start:	xorw %ax, %ax

	movw %ax, %ds
	movw %ax, %es
	movw %ax, %ss

	movw $0x7c00, %sp

	/* move self to 0x7e00 */
	movw $0x7e00, %di
	movw $0x7c00, %si

	movw $512, %cx

	cld

	rep
	movsb

	ljmp $0x0000, $real_start


real_start:
	leaw loading_msg, %si
	call print

	call load_sys

	call setup_e820

	ljmp $0, $0x8000

die:	hlt
	jmp die


load_sys:
	/* load the system to 0x8000, and jump */

	movw $0x0800, %ax
	movw %ax, %es

	xorw %bx, %bx
	xorl %eax, %eax

lloop:	incl %eax
	movw $16, %cx

	call read_lba

	movw %es, %cx
	addw $512, %cx
	movw %cx, %es

	cmpl $64, %eax
	jb cont

	ret

cont:	pushal
	/* put a '.' on screen */
	movb $'.', %al
	movb $0x0e, %ah

	movw $0x000f, %bx

	int $0x10

	popal

	jmp lloop


read_lba:
	pushaw
	pushl $0
	pushl %eax

	pushw %es
	pushw %bx

	pushw %cx
	pushw $16

	movb $0x42, %ah
	/* dx didn't change */

	movw %sp, %si

	int $0x13

	jc read_failed

	addw $16, %sp

	popaw

	ret


read_failed:
	leaw read_fail_msg, %si
	call print

	jmp die


setup_e820:
	xorl %ebx, %ebx
	movl %ebx, %es

	movl $0x7000, %edi

sel:	movl $0xe820, %eax
	movl $20, %ecx
	movl $0x534d4150, %edx

	int $0x15

	jc e820_failed

	addl $20, %edi

	cmpl $0, %ebx
	jne sel

	ret

e820_failed:
	leaw e820_fail_msg, %si

	pushw $die


print:	cld
	lodsb
	
	testb %al, %al
	jz pret

	movb $0x0e, %ah
	movw $0x000f, %bx

	int $0x10

	jmp print

pret:	ret


read_fail_msg:
	.ascii "read /dev/sda failed. "
	.byte 0x0d, 0x0a, 0x00

loading_msg:
	.asciz "Loading System"

e820_fail_msg:
	.asciz "get e820 failed. "


.org 0x1be

part0:

.org 510

.word 0xaa55

